package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GenStatUserLotteryDaily() error {
	fName := "GenStatUserLotteryDaily"
	sql := `insert into main.db_stat_user_lottery
(
  stt_date,
  ip_click_num,
  uv_click_num,
  pv_click_num,
  draw_num,
  diamond_consume,
  gold_consume
)
select 
date_sub(date(now()), interval 1 day) as stt_date,
%d as ip_click_num,
%d as uv_click_num,
%d as pv_click_num,
(select count(1) from main.db_user_lottery_history where draw_time between date(date_sub(now(), interval 1 day)) and date(now())) as draw_num,
(select ifnull(sum(coin_count),0) from main.db_user_profit where create_time between date(date_sub(now(), interval 1 day)) and date(now()) and coin_type = 2 and consume_type = 22 ) as diamond_consume,
(select ifnull(sum(coin_count),0) from main.db_user_profit where create_time between date(date_sub(now(), interval 1 day)) and date(now()) and coin_type = 1 and consume_type = 22 ) as gold_consume
`

	sql = fmt.Sprintf(sql, GetLotteryIpClickCount(), GetLotteryUvClickCount(), GetLotteryPvClickCount())
	o := models_main.StatUserLottery{}
	err := global.GetR().Where("stt_date = date_sub(date(now()),interval 1 day)").First(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = global.GetX().Exec(sql).Error
		ResetLotteryIpClickCount()
		ResetLotteryUvClickCount()
		ResetLotteryPvClickCount()
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

const (
	IPClick = "LOTTERY:CLICK:IP"
	UvClick = "LOTTERY:CLICK:UV"
	PvClick = "LOTTERY:CLICK:PV"
)

func GetLotteryIpClickCount() int {
	fName := "GenStatUserLotteryDaily"
	n, err := global.GetRds().HLen(IPClick).Result()
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return int(n)
}

func GetLotteryUvClickCount() int {
	fName := "GetLotteryUvClickCount"
	n, err := global.GetRds().Get(UvClick).Int()
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return n
}

func GetLotteryPvClickCount() int {
	fName := "GetLotteryPvClickCount"
	n, err := global.GetRds().Get(PvClick).Int()
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return n
}

func ResetLotteryIpClickCount() {
	fName := "ResetLotteryIpClickCount"
	err := global.GetRds().Del(IPClick).Err()
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
}

func ResetLotteryUvClickCount() {
	fName := "ResetLotteryUvClickCount"
	err := global.GetRds().Set(UvClick, 0, 0).Err()
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
}

func ResetLotteryPvClickCount() {
	fName := "GetLotteryPvClickCount"
	err := global.GetRds().Set(PvClick, 0, 0).Err()
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
}
